package com.cap.bts.crmdp.commons.sftp;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import org.slf4j.LoggerFactory;

import com.cap.bts.framework.common.exception.AppException;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;
import com.jcraft.jsch.UserInfo;

public class SFTPProcessor {
    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(SFTPProcessor.class);

    private Session session = null;

    private ChannelSftp channel = null;

    public ChannelSftp getConnect(SftpProperties sftpProperties) {
        JSch jsch = new JSch();
        try {
            session = jsch.getSession(sftpProperties.getUserName(), sftpProperties.getHost(), sftpProperties.getPort());
            LOGGER.debug("Session created.");

            session.setTimeout(sftpProperties.getDefaultTimeout());

            UserInfo ui= new SftpUserInfo(sftpProperties.getPassword());
            session.setUserInfo(ui);

            session.connect();
            LOGGER.debug("Session connected.");
            LOGGER.debug("Opening SFTP Channel.");
            channel = (ChannelSftp) session.openChannel("sftp"); // 打开SFTP通道
            channel.connect(); // 建立SFTP通道的连接
            LOGGER.debug("Connected successfully to ftpHost = " + sftpProperties.getHost() + ",as ftpUserName = "
                    + sftpProperties.getUserName() + ", returning: " + channel);
        } catch (Exception e) {
            LOGGER.error("", e);
        }
        return channel;
    }

    public void closeChannel() throws Exception {
        try {
            if (channel != null) {
                channel.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        } catch (Exception e) {
            LOGGER.error("close sftp error", e);
            throw new RuntimeException("close ftp error.");
        }
    }

    public void uploadFile(String localFile, String newName, String remoteFoldPath) throws RuntimeException {
        InputStream input = null;
        try {
            input = new FileInputStream(new File(localFile));
            // 改变当前路径到指定路径
            channel.cd(remoteFoldPath);
            channel.put(input, newName);
        } catch (Exception e) {
            LOGGER.error("Upload file error", e);
            throw new RuntimeException( "Upload file error.");
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    throw new RuntimeException( "Close stream error.");
                }
            }
        }
    }

    public void downloadFile(String remoteFile, String remotePath, String localFile) throws RuntimeException {
        OutputStream output = null;
        File file = null;
        try {
            file = new File(localFile);
            if (!checkFileExist(localFile)) {
                file.createNewFile();
            }
            output = new FileOutputStream(file);
            channel.cd(remotePath);
            channel.get(remoteFile, output);
        } catch (Exception e) {
            LOGGER.error("Download file error", e);
            throw new RuntimeException("Download file error.");
        } finally {
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    throw new RuntimeException( "Close stream error.");
                }
            }
        }
    }

    public List listFiles(String remotePath) throws AppException {
    	List list = new ArrayList();
        try {
        	Vector vector = channel.ls(remotePath);
        	list.addAll(vector);
        } catch (SftpException e) {
            LOGGER.error("List file error", e);
            throw new AppException("list file error.", e);
        }
        return list;
    }

    private boolean checkFileExist(String localPath) {
        File file = new File(localPath);
        return file.exists();
    }


    public static class SftpUserInfo implements UserInfo {
        public SftpUserInfo(String passwd) {
            this.passwd = passwd;
        }

        String passwd = null;

        public String getPassword() {
            return passwd;
        }

        public boolean promptYesNo(String str) {
            return true;
        }

        public String getPassphrase() {
            return null;
        }

        public boolean promptPassphrase(String message) {
            return true;
        }

        public boolean promptPassword(String message) {
            return true;
        }

        public void showMessage(String message) {
            System.out.println(message);
        }
    }
    
    //sftp文件转移方法
    public void rename(String oldName, String newName) throws RuntimeException {
        try {
            channel.rename(oldName, newName);
        } catch (Exception e) {
            LOGGER.error("Download file error", e);
            throw new RuntimeException("Download file error.");
        }
    }
    
    //删除sftp上的文件
    public void remove(String fileName) throws RuntimeException {
        try {
        	LOGGER.info("remove SFTP file:" + fileName);
            channel.rm(fileName);
        } catch (Exception e) {
            LOGGER.error("Remove file error", e);
            throw new RuntimeException("Remove file error.");
        }
    }

  /*  public static void main(String[] args) throws Exception {
        SftpProperties sftpProperties = new SftpProperties("mccrm-dpweb-uat.chinacloudapp.cn", "sftpcrm", "Ie(&%IUh_", 52222);

        SFTPProcessor ftpUtil = new SFTPProcessor();
        ChannelSftp channelSftp = ftpUtil.getConnect(sftpProperties);

        if(channelSftp.isConnected()){
            ftpUtil.uploadFile("C:/Users/gudong/Desktop/TenantServiceCenter.csv", "12345678.txt", "/upload");
        }

        List vv = ftpUtil.listFiles("/upload/test/..");
        if(vv!=null){
            for(int ii=0; ii<vv.size(); ii++){

                Object obj=vv.elementAt(ii);
                if(obj instanceof com.jcraft.jsch.ChannelSftp.LsEntry){
                    com.jcraft.jsch.ChannelSftp.LsEntry lsEntry = (com.jcraft.jsch.ChannelSftp.LsEntry) obj;

                    SftpATTRS attrs = lsEntry.getAttrs();


                    System.out.print(lsEntry.getFilename() + "\tisDir:" + attrs.isDir());
                    System.out.print("\tisLink:" + attrs.isLink());
                    System.out.println("\tflags:" + attrs.getFlags());
                }

            }
        }


        ftpUtil.downloadFile("12345678.txt", "/upload", "d:/123.txt");

        ftpUtil.closeChannel();
        System.out.println(channelSftp.isConnected());
    }*/
}